import { request } from "../../request4/index";

Page({
  data: {
    form: {
      username: "",
      xm: "",
      email: "",
      dw:"",
      dh: "",
      grade: ""
    },
    showLoginDialog: false,  // 控制登录对话框显示
    pendingTarget: '',       // 登录成功后要跳转的页面
  },

  onLoad() {
    this.fetchProfile();
  },

  fetchProfile() {

    let mygrade = wx.getStorageSync('grade')||-1;

    if (mygrade === -1) {
      // 保存待跳转的页面信息
      this.setData({
        showLoginDialog: true
      });
      
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 1500,
      });
      return;
    }

    const token = wx.getStorageSync('token');
    if (!token) return;
    request({ urlLeft: "/user/profile", method: "POST", header: { token } }).then(res => {
      const info = (res && res.data && res.data.info) || {};
      this.setData({
        form: {
          username: info.username || "",
          xm: info.xm || "",
          email: info.email || "",
          dh: info.dh || "",
          dw: info.dw || "",
          grade: info.grade !== undefined && info.grade !== null ? String(info.grade) : ""
        }
      })
    })
  },

  onInput(e) {
    const key = e.currentTarget.dataset.key;
    this.setData({ [`form.${key}`]: e.detail.value });
  },

  submit() {
    let mygrade = wx.getStorageSync('grade')||-1;
    if (mygrade === -1) {
      // 保存待跳转的页面信息
      this.setData({
        showLoginDialog: true
      });
      
      wx.showToast({
        title: '请先登录',
        icon: 'none',
        duration: 1500,
      });
      return;
    }
    
    const { username, xm, email, dw, dh, grade } = this.data.form;
    console.log(username, xm, email, dw, dh, grade);
    if (!username || !xm || !email || !dw || !dh || grade === "") {
      wx.showToast({ title: '请完整填写信息', icon: 'none' });
      return;
    }
    const token = wx.getStorageSync('token');
    request({
      urlLeft: "/user/profile/update",
      method: "POST",
      header: { token },
      data: { username, xm, email, dw, dh, grade: Number(grade) }
    }).then((resp) => {
      // console.log(resp.data.data.msg);
      wx.setStorageSync('grade', Number(grade));
      wx.showToast({ title: '保存成功', icon: 'success' });
      setTimeout(() => wx.navigateBack({ delta: 1 }), 600);
    })
  },

  back() {
    const pages = getCurrentPages();
    if (pages.length > 1) {
        wx.navigateBack({
            delta: 1
        });
    } else {
        // 如果没有上一页，则跳转到首页
        wx.navigateTo({
            url: '/pages/index4/index'
        });
    }
  },
  handleLogin() {
    console.log('用户点击登录');
    const that = this;
    
    wx.getUserProfile({
        desc: '获取您的信息以便提供更好的服务',
        success: (resu) => {
            console.log('获取用户信息成功：', resu);
            
            wx.login({
                success(res) {
                    console.log('微信登录响应：', res);
                    if (res.code) {
                        let code = res.code;
                        var { userInfo } = resu;
                        
                        console.log('准备发送登录请求，code:', code);
                        // console.log('请求地址：', 'https://guide.smart-park.nnweather.com/api/v1/wx/auth/wx/login');
                        console.log('请求数据：', { userInfo, code });
                        
                        request({ urlLeft: "/auth/wx/login", data: { userInfo, code }, method: "POST" })
                            .then(result => {
                                console.log('后端登录响应：', result);
                                
                                if (result && result.data && result.data.info) {
                                    // 兼容两种返回结构：info 为数字或对象
                                    const info = result.data.info;
                                    const grade = typeof info === 'number' ? info : (info.grade !== undefined ? info.grade : -1);
                                    const token = typeof info === 'object' ? info.token : '';
                                    const userId = typeof info === 'object' ? info.id : '';
                                    console.log('info', info);
                                    console.log('grade', grade);
                                    wx.setStorageSync('grade', grade);
                                    if (token) wx.setStorageSync('token', token);
                                    if (userId) wx.setStorageSync('userId', userId);
                                    
                                    // 关闭登录对话框
                                    that.setData({
                                        showLoginDialog: false
                                    });
                                    
                                    wx.showToast({
                                        title: '登录成功',
                                        icon: 'success',
                                        duration: 1500,
                                    });
                                    console.log('登录成功，权限等级：', grade);
                                    
                                    //刷新当前页面
                                    that.fetchProfile();
                                
                                    // 检查是否有待跳转的页面
                                    if (that.data.pendingTarget) {
                                        setTimeout(() => {
                                            let grade = wx.getStorageSync('grade');
                                            if (grade >= that.data.pendingFlag) {
                                                wx.navigateTo({
                                                    url: that.data.pendingTarget
                                                });
                                                // 清除待跳转信息
                                                that.setData({
                                                    pendingTarget: '',
                                                    pendingFlag: 0
                                                });
                                            } else {
                                                wx.showToast({
                                                    title: '权限不足',
                                                    icon: 'none',
                                                    duration: 1500,
                                                });
                                            }
                                        }, 1600);
                                    }
                                } else {
                                    console.error('后端返回数据格式异常：', result);
                                    wx.showToast({
                                        title: '登录失败，请重试',
                                        icon: 'none',
                                        duration: 2000,
                                    });
                                }
                            }).catch(err => {
                                console.error('网络请求失败：', err);
                                
                                let errorMsg = '网络请求失败';
                                if (err.errMsg) {
                                    if (err.errMsg.includes('timeout')) {
                                        errorMsg = '网络超时，请检查网络连接';
                                    } else if (err.errMsg.includes('fail')) {
                                        errorMsg = '连接服务器失败，请稍后重试';
                                    }
                                }
                                
                                wx.showModal({
                                    title: '登录失败',
                                    content: errorMsg + '\n\n是否重试？',
                                    showCancel: true,
                                    cancelText: '取消',
                                    confirmText: '重试',
                                    success(res) {
                                        if (res.confirm) {
                                            // 用户点击重试，重新执行登录
                                            that.handleLogin();
                                        } else {
                                            // 用户取消，关闭登录对话框
                                            that.setData({
                                                showLoginDialog: false,
                                                pendingTarget: '',
                                                pendingFlag: 0
                                            });
                                        }
                                    }
                                });
                            });

                    } else {
                        console.error('微信登录失败：', res);
                        wx.showToast({
                            title: '微信登录失败',
                            icon: 'none',
                            duration: 2000,
                        });
                    }
                },
                fail(err) {
                    console.error('wx.login调用失败：', err);
                    wx.showToast({
                        title: '登录失败',
                        icon: 'none',
                        duration: 2000,
                    });
                }
            });
            
        },
        fail: (err) => {
            console.error('getUserProfile失败：', err);
            // 清除待跳转信息
            that.setData({
                showLoginDialog: false,
                pendingTarget: '',
                pendingFlag: 0
            });
            wx.showToast({
                title: '取消登录',
                icon: 'none',
                duration: 1500,
            });
        }
        
    });

  },
  handleLater() {
    console.log('用户选择稍后登录');
    this.setData({
        showLoginDialog: false,
        pendingTarget: '',
        pendingFlag: 0
    });
    wx.showToast({
        title: '点击功能时需要登录',
        icon: 'none',
        duration: 2000,
    });
},
});

